package com.kun.user.mq;

import com.alibaba.fastjson2.JSON;
import com.kun.api.IUserService;
import com.kun.common.constant.ShopCode;
import com.kun.pojo.domain.TradeUserMoneyLog;
import com.kun.pojo.entity.MQEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group}",
        messageModel = MessageModel.BROADCASTING)
public class CancelMQListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IUserService userService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 1. 解析消息
            String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);
            MQEntity entity = JSON.parseObject(body, MQEntity.class);
            log.info("接收到消息");
            if (entity.getUserMoney() != null && entity.getUserMoney().compareTo(BigDecimal.ZERO) > 0) {
                // 2. 调用业务层进行余额修改
                TradeUserMoneyLog tradeUserMoneyLog = new TradeUserMoneyLog(entity.getUserId(), entity.getOrderId(),
                        ShopCode.SHOP_USER_MONEY_REFUND.getCode(), entity.getUserMoney());
                userService.reduceMoneyPaid(tradeUserMoneyLog);
                log.info("余额回退成功");
            }
        } catch (Exception e) {
            log.error("余额回退失败");
        }
    }
}
